//index.js
//获取应用实例
var app = getApp();
var ImageURL = app.globalData1.ImageURL;
var hostURL = app.globalData1.hostURL;
var WxParse = require('../../wxParse/wxParse.js');
var ID = app.globalData2.userid;
var Phone = app.globalData2.userphone;
Page({
   data: {
      ImageURL: ImageURL,
      minusStatus: 'disabled',
      autoplay: true,
      interval: 3000,
      duration: 1000,
      goodsdetail:[],
      swiperCurrent: 0,
      hasMoreSelect: false,
      //selectSize:"选择：",
      selectSizePrice: 0,
      totalScoreToPay: 0,
      shopNum: 0,
      hideShopPopup: true,
      num: 1,
      minusStatus: 1,
      //propertyChildIds: "",
      propertyChildNames: "",
      canSubmit: false, //  选中规格尺寸时候是否允许加入购物车
      shopCarInfo: {},
      shopType: "addShopCar",//购物类型，加入购物车或立即购买，默认为加入购物车
      sourceid:"",
      count:''
   },

 
   onLoad: function (options) {
      var that = this;
      that.setData({
         sourceid: options.sourceId, 
      });
      // console.log("sourceid: " + that.data.sourceid)

      var that = this;
      that.data.kjId = options.kjId;
      // 获取购物车数据
      wx.getStorage({
         key: 'shopCarInfo',
         success: function (res) {
            that.setData({
               shopCarInfo: res.data,
               shopNum: res.data.shopNum
            });
         }
      })
      wx.request({
         url: hostURL + 'sharedplatform-web/sourceDetail/findDetailById.action',
         method: 'GET',
         data: {
            sourceId: that.data.sourceid,
         },
         header: {
            'Accept': 'application/json'
         },
         success: function (res) {
            console.log("请求成功")
            that.setData({
               goodsdetail:res.data.sourceDetail,
               count: res.data.sourceDetail.source_count
            })  
           
         }
      })
   },
   //事件处理函数
   swiperchange: function (e) {
      this.setData({
         swiperCurrent: e.detail.current
      })
   },
   goShopCar: function () {
      wx.reLaunch({
         url: "/pages/shop-cart/index"
          
      });
   },
   toAddShopCar: function () {
      if (app.globalData2.hasLogin) {
         wx.getStorageInfo({
            success: function(res) {
               console.log("获取缓存中"+res.keys)
               console.log("获取用户缓存" + app.globalData2.userid)
            },
         })
         var userId = app.globalData2.userid;
         this.setData({
            userId: userId
         })

         this.setData({
            shopType: "addShopCar"
         })
         this.bindGuiGeTap();
         
      }
      else {
         wx.navigateTo({ url: "/pages/ucenter/login/login" });
         return;
      }
      // this.setData({
      //    shopType: "addShopCar"
      // })
      // this.bindGuiGeTap();
   },
   tobuy: function () {
      if (app.globalData2.hasLogin) {
         // wx.getStorageInfo({
         //    success: function (res) {
         //       console.log("获取缓存中" + res.keys)
         //       console.log("获取用户缓存" + app.globalData2.userphone)
         //    },
         // })
         let userInfo = wx.getStorageSync('userInfo');//wx.getStorageSync(KEY),从本地缓存中同步获取指定 key 对应的内容
         let token = wx.getStorageSync('token');
         this.setData({
            userInfo: userInfo,
         });
         console.log(userInfo)
         // var userId = app.globalData2.userphone;
         // this.setData({
         //    userphone: userphone
         // })
         this.setData({
            shopType: "tobuy"
         });
         this.bindGuiGeTap();
      }
      else {
         wx.navigateTo({ url: "/pages/ucenter/login/login" });
         return;
      }
   },
    /**
    * 规格选择弹出框
    */
   bindGuiGeTap: function () {
      this.setData({
         hideShopPopup: false
      })
   },
   /**
    * 规格选择弹出框隐藏
    */
   closePopupTap: function () {
      this.setData({
         hideShopPopup: true
      })
   },

   /* 点击减号 */
   bindMinus: function () {
      var num = this.data.num;
      // 如果大于1时，才可以减  
      if (num > 1) {
         num--;
      }
      // 只有大于一件的时候，才能normal状态，否则disable状态  
      var minusStatus = num <= 1 ? 'disabled' : 'normal';
      // 将数值与状态写回  
      this.setData({
         num: num,
         minusStatus: minusStatus
      });
   },
   /* 点击加号 */
   bindPlus: function (res) {
      var num = this.data.num;
      var N=this.data.count 
      // 不作过多考虑自增1  
     if (num >= N) {
         wx.showModal({
            title: '提示',
            content: '暂时缺货哦~',
            showCancel: false
         })
         return;
      } else { num++;}
      // 只有大于一件的时候，才能normal状态，否则disable状态  
      var minusStatus = num < 1 ? 'disabled' : 'normal';
      // 将数值与状态写回  
      this.setData({
         num: num,
         minusStatus: minusStatus
      });
   },
   /* 输入框事件 */
   //  bindManual: function (e) {
   //     var num = e.detail.value;
   //     // 将数值与状态写回  
   //    this.setData({
   //        num: num
   //    });
   //  } , 

   /**
   * 加入购物车
   */
   addShopCar: function () {
      if (this.data.num < 1) {
         wx.showModal({
            title: '提示',
            content: '购买数量不能为0！',
            showCancel: false
         })
         return;
      }
      //组建购物车
      var shopCarInfo = this.bulidShopCarInfo();

      this.setData({
         shopCarInfo: shopCarInfo,
         shopNum: shopCarInfo.shopNum
      });

      // 写入本地存储
      wx.setStorage({
         key: 'shopCarInfo',
         data: shopCarInfo,
      })
      this.closePopupTap();
      // wx.showToast({
      //    title: '加入购物车成功',
      //    icon: 'success',
      //    duration: 2000
      // })

      //console.log(shopCarInfo);
      var goodsId = this.data.goodsId
      var number = this.data.number
      var pic = this.data.pic;
      var name = this.data.name;
      var price = this.data.price;
      var userId = this.data.userId;
      console.log(userId);
      console.log(goodsId);
      console.log(number);
      console.log(pic);
      console.log(name);
      console.log(price);

      //把购物车数据传到后台
      wx.request({
        // url: 'http://localhost:8090/sharedplatform-web/cart/addCart.action',
         url: hostURL + 'sharedplatform-web/cart/addCart.action',
         data: {
            userId: userId,
            goodsId :goodsId,
            number :number,
            pic : pic,
            name : name,
            price :price,
            },
         method: 'Post',
         header: { 'content-type': 'application/x-www-form-urlencoded; charset=UTF-8' },
         success: function (res) {
            var errno = res.data.errno
            if(errno==0){
               console.log("购物车传值成功")
               wx.showToast({
                  title: '加入购物车成功',
                  icon: 'success',
                  duration: 2000
               })
            }else if(errno==1){
               console.log("加入购物车失败")
               wx.showToast({
                  title: '加入购物车失败',
                  icon: '',
                  duration: 2000
               })
            }else if(errno==2){
               console.log("更新购物车商品失败")
               wx.showToast({
                  title: '更新购物车商品失败',
                  icon: '',
                  duration: 2000
               })

            }
            
         }
      })

      //shopCarInfo = {shopNum:12,shopList:[]}
   },
    /**
	  * 立即购买
	  */
   buyNow: function () {
      if (this.data.num < 1) {
         wx.showModal({
            title: '提示',
            content: '购买数量不能为0！',
            showCancel: false
         })
         return;
      }
      //组建立即购买信息
      var buyNowInfo = this.buliduBuyNowInfo();
      // 写入本地存储
      wx.setStorage({
         key: "buyNowInfo",
         data: buyNowInfo
      })
      this.closePopupTap();

      wx.navigateTo({
         url: "/pages/to-pay-order/index?orderType=buyNow"
      })
   },
   /**
    * 组建购物车信息
    */
   bulidShopCarInfo: function () {
      // 加入购物车
      var shopCarMap = {};
      shopCarMap.goodsId = this.data.sourceid;
      shopCarMap.pic = this.data.goodsdetail.source_image;
      shopCarMap.name = this.data.goodsdetail.source_name;
      shopCarMap.price = this.data.goodsdetail.source_price;
      shopCarMap.number = this.data.num;
     
      var goodsId = shopCarMap.goodsId;
      this.setData({
         goodsId: goodsId
      });
      var pic = shopCarMap.pic[0];
      this.setData({
         pic: pic
      });
      var name = shopCarMap.name;
      this.setData({
         name: name
      });
      var price = shopCarMap.price;
      this.setData({
         price: price
      });
      var number = shopCarMap.number;
      this.setData({
         number: number
      });

      var shopCarInfo = this.data.shopCarInfo;
      if (!shopCarInfo.shopNum) {
         shopCarInfo.shopNum = 0;
      }
      if (!shopCarInfo.shopList) {
         shopCarInfo.shopList = [];
      }
      var hasSameGoodsIndex = -1;
      for (var i = 0; i < shopCarInfo.shopList.length; i++) {
         var tmpShopCarMap = shopCarInfo.shopList[i];
         if (tmpShopCarMap.goodsId == shopCarMap.goodsId && tmpShopCarMap.propertyChildIds == shopCarMap.propertyChildIds) {
            hasSameGoodsIndex = i;
            shopCarMap.number = shopCarMap.number + tmpShopCarMap.number;
            break;
         }
      }

      shopCarInfo.shopNum = shopCarInfo.shopNum + this.data.num;
      if (hasSameGoodsIndex > -1) {
         shopCarInfo.shopList.splice(hasSameGoodsIndex, 1, shopCarMap);
      } else {
         shopCarInfo.shopList.push(shopCarMap);
      }
      shopCarInfo.kjId = this.data.kjId;
      return shopCarInfo;
   },
	// /**
	//  * 组建立即购买信息
	//  */
   buliduBuyNowInfo: function () {
      var shopCarMap = {};
      shopCarMap.goodsId = this.data.sourceid;
      shopCarMap.pic = this.data.goodsdetail.source_image[0];
      shopCarMap.name = this.data.goodsdetail.source_name;
      shopCarMap.price = this.data.goodsdetail.source_price;
      shopCarMap.number = this.data.num;
      var buyNowInfo = {};
      if (!buyNowInfo.shopNum) {
         buyNowInfo.shopNum = 0;
      }
      if (!buyNowInfo.shopList) {
         buyNowInfo.shopList = [];
      }

      buyNowInfo.shopList.push(shopCarMap);
      buyNowInfo.kjId = this.data.kjId;
      return buyNowInfo;
   },



})
